﻿using UnityEngine;

namespace CJ.XNFZ {
	public class Singleton<T> : MonoBehaviour where T : Singleton<T> {
		protected static T instance;

		public static T Instance {
			get {
				if (!IsInitialized) {
					var temp = new GameObject ("[Singleton] " + typeof (T).Name);
					temp.AddComponent<T> ();
				}
				return instance;
			}
		}

		public static bool IsInitialized {
			get {
				return instance != null;
			}
		}

		[SerializeField]
		protected bool dontDestroy = false;

		public bool DontDestroy {
			get {
				return dontDestroy;
			}
			set {
				dontDestroy = value;
			}
		}

		protected virtual void Awake () {
			if (instance != null) {
				Debug.LogWarningFormat ("Trying to instantiate a second instance of singleton class {0}", GetType ().Name);
				enabled = false;
			} else {
				instance = (T) this;
			}
			if (dontDestroy) {
				DontDestroyOnLoad (gameObject);
			}
		}
		
		protected virtual void OnDestroy () {
			if (instance == this) {
				instance = null;
			}
		}
	}
}